package com.chinawayltd.ews.sample.service.basicInfo.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.mapper.TBranchMapper;
import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.basicInfo.BranchConsumeTimeExtendMapper;
import com.chinawayltd.ews.sample.mapper.basicInfo.BranchExtendMapper;
import com.chinawayltd.ews.sample.mapper.order.OrderExtendMapper;
import com.chinawayltd.ews.sample.model.TBranch;
import com.chinawayltd.ews.sample.model.TBranchConsumeTime;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TOrder;
import com.chinawayltd.ews.sample.model.basicInfo.BranchVO;
import com.chinawayltd.ews.sample.model.common.CommonVO;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.service.basicInfo.BranchService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.util.MapUtils;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.BranchGirdQuery;

@Service
public class BranchServiceImpl extends BaseServiceImpl implements BranchService {
	private static  SimpleDateFormat sdf_hhmm = new SimpleDateFormat("HH:mm");
	private static  SimpleDateFormat sdf_yyyyhhmm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private BranchExtendMapper branchExtendMapper;
    @Autowired
    private TBranchMapper tBranchMapper;
    @Autowired
    private TLogMapper tLogMapper;
    private final String tableName = "T_BRANCH";
    @Autowired
    BranchConsumeTimeExtendMapper branchConsumeTimeExtendMapper;
    @Autowired
    private OrderExtendMapper orderExtendMapper;
	@Autowired
	private CommonService commonService;
	
    @Override
    public List<BranchVO> listBranchByPage(BranchGirdQuery queryParam) {
        List<BranchVO> listBranchByPage = branchExtendMapper.listBranchByPage(queryParam);
        //翻译不可用车型
//        for(TBranch tb : listBranchByPage){
//        	String unavailableCarType = tb.getUnavailableCarType();
//        	if(StringUtils.isNoneBlank(unavailableCarType)){
//        		String[] splitCarType = unavailableCarType.split(",");
//        		StringBuffer type = new StringBuffer();
//        		for(int i = 0; i < splitCarType.length; i++){
//        			String name = branchExtendMapper.selectDictByInfoId(splitCarType[i]);
//        			// 字典项不存在的情况
//        			if(StringUtils.isNotBlank(name)){
//        				type.append(name);
//        				type.append(",");
//        			}
//        		}
//        		// 字典项不存在，type可能为空的情况
//        		if(StringUtils.isNotBlank(type)){
//        			tb.setUnavailableCarType(type.toString().substring(0, type.length()-1));
//        		}else{
//        			tb.setUnavailableCarType(null);
//        		}
//        	}
//        }
        return listBranchByPage;
    }

	@Override
	public TBranch getBranchById(Long id) throws Exception {
		if (id == null || id <= 0) {
			throw new RuntimeException("id不能为空或者少于等于0！");
		}
		return tBranchMapper.selectByPrimaryKey(id);
	}

    @Override
	@Transactional
    public int insertBranch(TBranch tBranch) {
        tBranch.setCreateTime(new Date());
        
        int result = branchExtendMapper.insert(tBranch);
        if(result >0){
    		TLog log = new TLog();
    		log.setDataId(tBranch.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setOperationType(1);
    		log.setCreateTime(new Date());
    		tLogMapper.insert(log);
        }
        return result;
    }

    @Override
	@Transactional
    public int updateBranch(TBranch tBranch) {
        tBranch.setUpdateTime(new Date());
        int result = tBranchMapper.updateByPrimaryKeySelective(tBranch);
        if(result >0){
    		TLog log = new TLog();
    		log.setDataId(tBranch.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setOperationType(2);
    		log.setCreateTime(new Date());
    		tLogMapper.insert(log);
        }
        
        return result;
    }

    @Override
	@Transactional
    public int deleteBranchById(Long id) throws Exception{
    	if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
    	Long branchId = id;
		List<TBranchConsumeTime> listBranch = branchConsumeTimeExtendMapper.listBranchTimeByBranch(branchId);
		if(listBranch.size() >0) {
			throw new BusinessException("站点耗时信息含有该站点，删除失败!");
		}
		List<TOrder> listOrder = orderExtendMapper.listOrderByBranch(branchId);
		if(listOrder.size() >0) {
			throw new BusinessException("物料订单信息含有该站点，删除失败!");
		}
        return tBranchMapper.deleteByPrimaryKey(id);		
    }

	@Override
	@Transactional
	public int deleteBranchsByIds(String ids) {
		if(StringUtils.isBlank(ids)){
            throw new RuntimeException("数据不能为空!");
        }
		// 1.分割ids
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			// 2.删除前检查是否已关联功能,如果关联，提示不可删除;如果不关联，继续
			Long branchId = Long.parseLong(id);
			List<TBranchConsumeTime> listBranch = branchConsumeTimeExtendMapper.listBranchTimeByBranch(branchId);
			if(listBranch.size() >0){
				throw new BusinessException("站点耗时信息含有该站点，删除失败!");
			}
			List<TOrder> listOrder = orderExtendMapper.listOrderByBranch(branchId);
			if(listOrder.size() >0){
				throw new BusinessException("物料订单信息含有该站点，删除失败!");
			}
		}
		// 3.第一种需求：存在某个失败，就全部不能删除；(目前采取)  第二种需求：for使用continue逐个判断和删除
		int count = branchExtendMapper.deleteAll(idArr);
		if(count>0){
			TLog log = null;
			for (String id : idArr) {
				long dataId = Long.parseLong(id);
				log = new TLog();
				log.setDataId(dataId);
				log.setTableName(tableName);
				log.setOperationUser(getCurrentUser().getRealname());
				log.setOperationType(3);
				log.setCreateTime(new Date());
				log.setUpdateTime(new Date());
				tLogMapper.insertSelective(log);
			}
		}
		return count;
	}
	private static String[] sources = new String[]{  
	        "A","B","C","D","E","F","G","H",  
	        "I","J","K","L","M","N","O","P",  
	        "Q","R","S","T","U","V","W","X","Y","Z"  
	};
	@Override
	public ExcelObjModel insertList(List<PageData> list){
		ExcelObjModel model = new ExcelObjModel();
		List<Object> mapList = new ArrayList<>();
		model.setCode(0);
		Date date = new Date();
		TBranch branch =null;
		String abnormalStr = null;//标识异常列
		hasSomeWrong:
		for (PageData pd : list) {
			try {
				branch = new TBranch();
				String branchCode = pd.getString("var0");
				branch.setBranchCode(branchCode);
				String branchName = pd.getString("var1");
				branch.setBranchName(branchName);
				branch.setBranchAddr(pd.getString("var2"));
				String lng = pd.getString("var3");
				if(StringUtils.isNoneBlank(lng)){
					branch.setLongitude(new BigDecimal(lng));
				}else{
					branch.setLongitude(null);
				}
				String lat = pd.getString("var4");
				if(StringUtils.isNoneBlank(lat)){
					branch.setLatitude(new BigDecimal(lat));
				}else{
					branch.setLatitude(null);
				}
				
				String unCarType = pd.getString("var5");
				StringBuffer sb = new StringBuffer();
	        	if(StringUtils.isNotBlank(unCarType)){
	        		String[] strs = unCarType.split(",");
	        		for (int i = 0; i < strs.length; i++) {
	        			String data = strs[i].trim();
						if(StringUtils.isNotBlank(strs[i])){
							sb.append(data).append(",");
						}
						if(i==strs.length-1){
							sb.deleteCharAt(sb.length()-1);
						}
					}
	        		branch.setUnavailableCarType(sb.toString());
	        	}else{
	        		branch.setUnavailableCarType("");
	        	}
	        	abnormalStr = "G";
				String consumeTime = pd.getString("var6");
				if(StringUtils.isNoneBlank(consumeTime)){
					branch.setConsumeTime((byte)Integer.valueOf(consumeTime).intValue());
				}
				abnormalStr = "H";
				String boardConsumeTime = pd.getString("var7");
				if(StringUtils.isNoneBlank(boardConsumeTime)){
					branch.setBoardConsumeTime((byte)Integer.valueOf(boardConsumeTime).intValue());
				}
				
				String bigTime1 = pd.getString("var8");
				String endTime1 = pd.getString("var9");
				String bigTime2 = pd.getString("var10");
				String endTime2 = pd.getString("var11");
				abnormalStr = "I";
				if(StringUtils.isNoneBlank(bigTime1)){
					bigTime1 = formatTimeToHHMM(bigTime1);
					branch.setBigTimeOne(bigTime1);
				}
				abnormalStr = "J";
				if(StringUtils.isNoneBlank(endTime1)){
					endTime1 = formatTimeToHHMM(endTime1);
					branch.setEndTimeOne(endTime1);
				}
				abnormalStr = "K";
				if(StringUtils.isNoneBlank(bigTime2)){
					bigTime2 = formatTimeToHHMM(bigTime2);
					branch.setBigTimeTwo(bigTime2);
				}
				abnormalStr = "L";
				if(StringUtils.isNoneBlank(endTime2)){
					endTime2 = formatTimeToHHMM(endTime2);
					branch.setEndTimeTwo(endTime2);
				}
				abnormalStr = "M";
				String branchFromType = pd.getString("var12");
				List<CommonVO> dictData = commonService.listDictData("branch_from_type", branchFromType, null);
				if(dictData.size() >0){
					branch.setBranchFromType((byte)Integer.valueOf(dictData.get(0).getValue()).intValue());
				}else{
					throw new RuntimeException();
				}
				Map<String, Object> map = MapUtils.objectToMap(branch);
				map.put("branchFromTypeStr", branchFromType);
				for(int i = 0; i < 13; i++){
					if(StringUtils.isBlank(pd.getString("var"+i)) && i != 3 && i !=4 && i != 5){
						//int com = i + 1;
						map.put("describe", "第"+sources[i]+"列内容不能为空");
						mapList.add(map);
						continue hasSomeWrong;
					}
				}
				
				if(branch.getConsumeTime() <0){
					map.put("describe", "固定服务时长不能小于0");
					mapList.add(map);
					continue hasSomeWrong;
				}
				if(branch.getBoardConsumeTime() <0){
					map.put("describe", "每板位服务时长不能小于0");
					mapList.add(map);
					continue hasSomeWrong;
				}
				//判断不可用车型格式
				String unavailableCarType = branch.getUnavailableCarType();
				if(StringUtils.isNoneBlank(unavailableCarType)){
					if(unavailableCarType.contains("，")){
						map.put("describe", "站点不可用类型格式有误");
						mapList.add(map);
						continue hasSomeWrong;
					}
					String[] unCarTypeArr = unavailableCarType.split(",");
					for(String id : unCarTypeArr){
						if(!"16".equals(id) && !"20".equals(id) && !"30".equals(id)){
							map.put("describe", "站点不可用类型为16、20、30");
							mapList.add(map);
							continue hasSomeWrong;
						}
					}
				}
				
				if(endTime1.equals("00:00") || endTime2.equals("00:00") || endTime1.equals("0:00") || endTime2.equals("0:00")){
					map.put("describe", "结束时间不能为00:00");
					mapList.add(map);
					continue hasSomeWrong;
				}
				if(sdf_hhmm.parse(bigTime1).getTime() > sdf_hhmm.parse(endTime1).getTime()){
					map.put("describe", "开始时间必须小于结束时间");
					mapList.add(map);
					continue hasSomeWrong;
				}
				if(sdf_hhmm.parse(bigTime2).getTime() > sdf_hhmm.parse(endTime2).getTime()){
					map.put("describe", "开始时间必须小于结束时间");
					mapList.add(map);
					continue hasSomeWrong;
				}
				branch.setCreateTime(date);
				branch.setUpdateTime(date);
				
				Map<String, Object> resultMap = this.toLeadData(branch);
				if(org.apache.commons.collections4.MapUtils.getInteger(resultMap, "flag") == 2){
					map.put("describe", "已更新");
					mapList.add(map);
					model.setCode(1);
				}else if(org.apache.commons.collections4.MapUtils.getInteger(resultMap, "flag") == 1){
					map.put("describe", "导入成功");
					mapList.add(map);
					model.setCode(1);
				}else{
					map.put("describe", "站点名称与编号不唯一且不对应，更新失败！");
					mapList.add(map);
					model.setCode(0);
					continue hasSomeWrong;
				}
			} catch (Exception e) {
				e.printStackTrace();
				model.setCode(0);
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("branchCode", pd.getString("var0"));
				exceptionMap.put("branchName", pd.getString("var1"));
				exceptionMap.put("branchAddr", pd.getString("var2"));
				exceptionMap.put("longitude", pd.getString("var3"));
				exceptionMap.put("latitude", pd.getString("var4"));
				exceptionMap.put("unavailableCarType", pd.getString("var5"));
				exceptionMap.put("consumeTime", pd.getString("var6"));
				exceptionMap.put("boardConsumeTime", pd.getString("var7"));
				exceptionMap.put("bigTimeOne", pd.getString("var8"));
				exceptionMap.put("endTimeOne", pd.getString("var9"));
				exceptionMap.put("bigTimeTwo", pd.getString("var10"));
				exceptionMap.put("endTimeTwo", pd.getString("var11"));
				exceptionMap.put("branchFromTypeStr", pd.getString("var12"));
				exceptionMap.put("describe", "第"+abnormalStr+"列：数据异常，导入失败");
				mapList.add(exceptionMap);
			}
			
		}
		model.setList(mapList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if(mapList.size() >0){
			cloums.add(new ExportCloumsModel("站点编号", "branchCode"));
			cloums.add(new ExportCloumsModel("站点名称", "branchName"));
			cloums.add(new ExportCloumsModel("站点地址", "branchAddr"));
			cloums.add(new ExportCloumsModel("经度", "longitude"));
			cloums.add(new ExportCloumsModel("纬度", "latitude"));
			cloums.add(new ExportCloumsModel("站点不可用车型", "unavailableCarType"));
			cloums.add(new ExportCloumsModel("固定服务时长", "consumeTime"));
			cloums.add(new ExportCloumsModel("每板位服务时长", "boardConsumeTime"));
			cloums.add(new ExportCloumsModel("开始工作时间1", "bigTimeOne"));
			cloums.add(new ExportCloumsModel("结束工作时间1", "endTimeOne"));
			cloums.add(new ExportCloumsModel("开始工作时间2", "bigTimeTwo"));
			cloums.add(new ExportCloumsModel("结束工作时间2", "endTimeTwo"));
			cloums.add(new ExportCloumsModel("站点所属类型", "branchFromTypeStr"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}

	private String formatTimeToHHMM( String time) throws ParseException {
		SimpleDateFormat sdf = time.length() < 6 ? sdf_hhmm : sdf_yyyyhhmm;
		time = sdf_hhmm.format(sdf.parse(time));
		return time;
	}

	/**导入数据，存在则更新(站点名称唯一)
	 * @author Fay
	 * @date 2018年5月7日 下午2:49:56
	 * @param branch
	 * @return
	 */
	@Transactional
	private Map<String, Object> toLeadData(TBranch branch) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<TBranch> listByName = branchExtendMapper.getByNameOrId(null,branch.getBranchName());
		List<TBranch> listByCode = branchExtendMapper.getByCodeOrId(null,branch.getBranchCode());
		int result = 0;
		TLog log = new TLog();
		Long name_id = null;
		if(listByName != null && listByName.size() > 0){
			name_id = listByName.get(0).getId();
		}
		Long code_id = null;
		if(listByCode != null && listByCode.size() > 0){
			code_id = listByCode.get(0).getId();
		}
		if(name_id != null || code_id != null){//修改
			if(name_id != null && code_id != null){//存在站点名称相同的对象 、存在站点编码相同的对象
				if(name_id == code_id){//如果相同
					branch.setId(name_id);
					result = tBranchMapper.updateByPrimaryKey(branch);
					log.setOperationType(2);
					resultMap.put("flag", 2);
				}else{
					resultMap.put("flag", 0);//站点与编号不对应，更新失败！
					return resultMap;
				}
			}else{
				resultMap.put("flag", 0);
				return resultMap;
			}
			
		}else{//新增
			result = branchExtendMapper.insert(branch);
			log.setOperationType(1);
			resultMap.put("flag", result);
		}
		if(result > 0){
    		log.setDataId(branch.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setCreateTime(new Date());
    		log.setUpdateTime(new Date());
    		tLogMapper.insert(log);
		}
		return resultMap;
	}
	
	public static void main(String[] args) throws ParseException {
//		SimpleDateFormat sdf_hhmm = new SimpleDateFormat("HH:mm");
//		SimpleDateFormat sdf_yyyymmddhhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String date1 = "09:00";
//		String date2 = "2008-09-19 09:00:00";
//		System.out.println(sdf_yyyymmddhhmmss.parse(date1));
//		System.out.println(sdf_hhmm.format(sdf_yyyymmddhhmmss.parse(date2)));
		
		String unCarType = "30,32,";
		StringBuffer sb = new StringBuffer();
    	if(StringUtils.isNotBlank(unCarType)){
    		String[] strs = unCarType.split(",");
    		for (int i = 0; i < strs.length; i++) {
    			String data = strs[i].trim();
				if(StringUtils.isNotBlank(strs[i])){
					sb.append(data).append(",");
				}
				if(i==strs.length-1){
					sb.deleteCharAt(sb.length()-1);
				}
			}
    		System.out.println(sb.toString());
    	}
    	TBranch tt = new TBranch();
    	tt.setBranchFromType((byte) 1);
	}

	@Override
	public List<TBranch> getByNameOrId(String id, String name) throws Exception{
		if(StringUtils.isBlank(name)){
            throw new RuntimeException("数据不能空！");
        }
		return branchExtendMapper.getByNameOrId(id, name);
	}

	@Override
	public List<TBranch> getByCodeOrId(String id, String code) throws Exception {
		if(StringUtils.isBlank(code)){
            throw new RuntimeException("数据不能空！");
        }
		return branchExtendMapper.getByCodeOrId(id, code);
	}
}
